package com.infoclue.modules.km.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.infoclue.modules.km.service.IKmsDocService;
import com.infoclue.modules.km.utils.MinioService;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.KM.common.config.BaseConfig;
import org.jeecg.modules.KM.common.rules.KMConstant;
import org.jeecg.modules.KM.common.utils.*;
import org.jeecg.modules.KM.entity.*;
import org.jeecg.modules.KM.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class KmsDocService implements IKmsDocService {

    @Autowired
    private IKmDocService kmDocService;
    @Autowired
    private IKmFileService kmFileService;
    //	@Autowired
//	private ElasticsearchClient client;
    @Autowired
    private KMConstant commonConstant;
    @Autowired
    private IKmDocVisitRecordService kmDocVisitRecordService;
    @Autowired
    private IThreadPoolExecutorService executorService;
    @Autowired
    private DictUtils dictUtils;
    @Autowired
    private BaseConfig baseConfig;
    @Autowired
    private IKmSysConfigService kmSysConfigService;
    @Autowired
    private MinioService minioService;


    public static final String topic = "kms";
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Resource
    private ObjectMapper objectMapper;

    public void sendMessage(String topic, KmDoc message) {

        try {
            kafkaTemplate.send(topic, this.objectMapper.writeValueAsString(message));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

    }

    /***
     * 索引MINIO文件
     * @param bucketname 桶名
     * @param folder 文件夹
     * @param suffix 文件后缀
     * @param kb 知识库名称
     */
    public void indexToKMS(String bucketname, String folder,String suffix,String kb) {

        List<io.minio.Result<Item>> fileObjects = this.minioService.getFileObjects(bucketname, folder);

        List<io.minio.Result<Item>> indexFiles = new ArrayList<io.minio.Result<Item>>();
        List<io.minio.Result<Item>> previewFiles = new ArrayList<io.minio.Result<Item>>();
        //log.info("minoObjects.size()--------------------" + fileObjects.size());
        //构建文件分类
        for (int i = 0; i < fileObjects.size(); i++) {
            Result<Item> item = fileObjects.get(i);
            try {
                //log.info("item.get().objectName()--------------------" + item.get().objectName()+"---"+suffix);
              if(item.get().objectName().lastIndexOf(suffix)>-1)
                  indexFiles.add(item);
              else
                  previewFiles.add(item);
            } catch (Exception ex) {
                log.error("exception--------------------" + ex.getMessage());
            }
        }
        log.info("indexFiles.size()--------------------" + indexFiles.size()+"--------------previewFiles.size()--------------------" + previewFiles.size());

        for (int i = 0; i < indexFiles.size(); i++) {
            Result<Item> item = indexFiles.get(i);
            Result<Item> preitem =null;
            try {

                MultipartFile multipartFile = this.minioService.downloadMultiPartFile(bucketname, item.get().objectName());
                MultipartFile previewpartFile = null;
                for (int  j= 0; j < previewFiles.size(); j++) {

                    String objName=item.get().objectName().replaceAll(suffix,"");
                    log.info("------item.get().objectName()--------------------" +item.get().objectName() +"------objName--------------------" + objName);
                    if(previewFiles.get(j).get().objectName().indexOf(objName)>-1){
                        log.info("previewfile--------------------" + previewFiles.get(j).get().objectName()+"-----"+previewFiles.get(j).get().objectName().indexOf(objName));
                        preitem =previewFiles.get(j);
                        previewpartFile=this.minioService.downloadMultiPartFile(bucketname, preitem.get().objectName());
                    }
                }
                KmDoc kmDoc=this.indexMultipartFile(multipartFile,previewpartFile);
                if(kmDoc!=null) {
                    log.info("----------moveObject--------------"+bucketname+"-----"+item.get().objectName());
                    this.minioService.moveObject(bucketname, item.get().objectName(), bucketname, "handled/"+item.get().objectName());
                    if(preitem!=null) {
                        this.minioService.moveObject(bucketname, preitem.get().objectName(), bucketname, "handled/" + preitem.get().objectName());
                        log.info("----------movepreObject--------------"+bucketname+"-----"+preitem.get().objectName());
                    }
                    kmDoc.setKnowledgeBase(kb);
                    this.sendMessage(topic, kmDoc);
                }
            } catch (Exception ex) {
                log.error("exception--------------------" + ex.getMessage());
            }
        }


    }

    /***
     * 文件存入MySQL数据库-源文件kmfile/kmdoc
     * @param file
     * @return
     */
    private KmDoc  indexMultipartFile(MultipartFile file,MultipartFile previewfile) {


        KmDoc kmDoc=null;
        try {
            log.info("=====开始处理文件======"+ file.getOriginalFilename());
            log.info("=====文件大小======" + file.getSize());
            //log.info("=====file.getFileSuffix()======" + StringUtils.getFileSuffix(file.getOriginalFilename()));
            if (!commonConstant.isFileTypeSupport(StringUtils.getFileSuffix(file.getOriginalFilename()))) {
                return null;
            }

            //根据文档hash进行去重
            KmFile dupFile = kmFileService.getKmFileBySha256(HashUtil.sha256(file.getOriginalFilename()));
            if (dupFile != null) {
                log.info("=====文件重复======"+ file.getOriginalFilename());
                return null;
            }

            //保存原文件到kmfile表
            KmFile kmFile = kmFileService.saveFile(file);
            log.info("=====prefile文件地址======" + kmFile.getPhysicalPath());

            //存入MySQL数据库,km_doc
            kmDoc = kmDocService.saveDoc(kmFile, file);

            if(previewfile!=null) {
                KmFile previewKmFile = kmFileService.saveFile(previewfile);
                log.info("=====prefile文件地址======" + kmFile.getPhysicalPath());
                //存入MySQL数据库,km_doc
                kmDoc = kmDocService.saveDoc(kmFile, previewKmFile,file);
            } else{
                kmDoc = kmDocService.saveDoc(kmFile, file);
            }

        } catch (Exception e) {
            log.error("Exception--------" + e.getMessage());

        }
        return kmDoc;
    }
}
